<template>
<div class="layout-app" ref='myBox'>
	<!-- main -->
<el-dialog :title="diglogTile" :visible.sync="exaDialogVisible" width="58%" :before-close="handleClose" :destroy-on-close='true' :modal="false"
:close-on-click-modal="false">
		<!-- 提交审核过单 -->
	<div class="addAcc">
			<!-- tabs -->
			<div class="tabs">
				<div class="tabsMain">
					<!-- 表单 -->
					<el-form ref="form" :model="addForm" label-width="88px" size="mini" :disabled="true" >
						<el-row :gutter="8">
							<el-col :xs="val.xs" :sm="val.xs" :md="val.md" :lg="val.lg" :xl="val.xl" type="flex" v-for="(val,i) in formType" :key="i">
								<!-- input -->
								<el-form-item v-if="val.type == 'input'" :label="val.label" :prop="val.modelValue">
									<el-input :suffix-icon='val.prefix' v-model="$data.addForm[val.modelValue]" :placeholder="val.placeholder"></el-input>
								</el-form-item>
								<!-- textarea -->
								<el-form-item v-if="val.type == 'textarea'" :label="val.label" :prop="val.modelValue">
									<el-input type="textarea" :rows="3" placeholder="请输入内容" v-model="$data.addForm[val.modelValue]"></el-input>
								</el-form-item>
								<!-- select -->
								<el-form-item v-if="val.type == 'select'" :label="val.label" :prop="val.modelValue">
									<el-select v-model="$data.addForm[val.modelValue]" filterable placeholder="请选择" :disabled="val.disabled">
										<el-option v-for="item in $data[val.op]" :key="item.id" :label="item.label" :value="item.id"> 
										<span style="color: #8492a6; font-size: 12px">{{ item.label }}</span></el-option>
									</el-select>
								</el-form-item>
								<!-- date -->
								<el-form-item v-if="val.type == 'date'" :label="val.label" :prop="val.modelValue">
									<el-date-picker  :disabled="val.disabled ? true : false"
									type="date" value-format="yyyy-MM-dd" placeholder="选择日期" v-model="$data.addForm[val.modelValue]">
									</el-date-picker>
								</el-form-item>
							</el-col>
						</el-row>
					</el-form>
					<!-- table -->
					<div class="table">
						<el-table :data="tableData" border @row-dblclick="handledbRow" :style="{ width: tableWidth + 'px' }">
							<el-table-column v-for="(col, inx) in tableRows" :key="inx" :type="col.type" :prop="col.prop" :label="col.name" :width="columnWidth(col, tableData)"></el-table-column>
							<!-- fixed -->
							<el-table-column fixed="left" label="行号" type="index" width="68" align="center"></el-table-column>
						</el-table>
						<div class="total">
							<span>合计金额：</span><el-input v-model="cbValue" style="width: 128px;" size="mini" :disabled='totaldisabled'></el-input>
						</div>
					</div>
				</div>
			</div>
			<!-- 提交 -->
			<div v-if="diglogTile === '草稿'" slot="footer" class="dialog-footer">
				<el-button size="mini" type="primary" @click="Submit">确定提交</el-button>
				<el-button size="mini" @click="exaDialogVisible = false">取消</el-button>
			</div>
			<!-- 审核 -->
			<div v-if="diglogTile === '审核'" slot="footer" class="dialog-footer">
				<el-button size="mini" type="danger" @click="refuseExamine">拒绝审核</el-button>
				<el-button size="mini" type="primary" @click="exaSubmit">确定审核</el-button>
				<el-button size="mini" @click="exaDialogVisible = false">取消</el-button>
			</div>
			<!-- 过单 -->
			<div v-if="diglogTile === '过单'" slot="footer" class="dialog-footer">
				<el-button size="mini" type="danger" @click="refusePassOrder">拒绝过单</el-button>
				<el-button size="mini" type="primary" @click="passOrderSubmit">确定过单</el-button>
				<el-button size="mini" @click="exaDialogVisible = false">取消</el-button>
			</div>
	</div>
</el-dialog>

<!-- 快捷调拨 -->
<div class="toPss">
	<el-dialog 
	  title="快捷调拨单" 
	  :visible.sync="toPassDialog" 
	  width="60%"
	  custom-class="quick-transfer-dialog"
	  :close-on-click-modal="false"
	  @open="console.log('调拨对话框打开')"
	  @close="console.log('调拨对话框关闭')"
	>
	    <!-- Header 部分 -->
	    <div class="dialog-header">
	      <div class="warehouse-info">
	        <div class="warehouse-item">
	          <span class="label">当前库房：</span>
	          <el-input v-model="currentWarehouse" disabled size="mini"></el-input>
	        </div>
	        <div class="warehouse-item">
	          <span class="label">收货库房：</span>
	          <el-select v-model="targetWarehouse" placeholder="请选择收货库房" size="mini" style="width: 100%">
	            <el-option v-for="item in warehouseOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
	          </el-select>
	        </div>
	      </div>
	    </div>
	
	    <!-- Main 部分 - 明细表格 -->
	    <div class="dialog-main" style="margin-top: 12px;">
	      <el-table
	        :data="tableDetailsData"
	        border
	        size="small"
	        style="width: 100%;overflow: hidden;"
	        height="300px"
	        highlight-current-row
	      >
	        <el-table-column
	          prop="drugCode"
	          label="药品编码"
	          width="120"
	          align="center"
	        ></el-table-column>
	        <el-table-column
	          prop="drugName"
	          label="药品名称"
	          width="150"
	          align="center"
	        ></el-table-column>
	        <el-table-column
	          prop="drugSpec"
	          label="规格"
	          width="120"
	          align="center"
	        ></el-table-column>
	        <el-table-column
	          prop="manuLotnum"
	          label="批号"
	          width="120"
	          align="center"
	        ></el-table-column>
	        <el-table-column
	          prop="purcCnt"
	          label="数量"
	          width="128"
	          align="center"
	        >
	        </el-table-column>
			<el-table-column
			  prop="unt"
			  label="入库单位"
			  width="128"
			  align="center"
			>
			</el-table-column>
			
			<el-table-column prop="purcType" label="库存类型">
				 <template slot-scope="{ row }">
					<!-- 根据state显示不同的图标 -->
					<div class="stateValue" style="border-radius: 4px;text-align: center;">
						<span>{{ purcTypeMap[row.purcType] || '未知状态' }}</span>
					</div>
				</template>
			</el-table-column>
	        <el-table-column
	          prop="purcAmt"
	          label="单价"
	          width="100"
	          align="center"
	        ></el-table-column>
	        <el-table-column
	          prop="saleAmt"
	          label="金额"
	          width="100"
	          align="center"
	        ></el-table-column>
			<el-table-column
			  prop="purcCnt"
			  label="库存数量"
			  width="100"
			  align="center"
			></el-table-column>
	        <el-table-column
	          label="操作"
	          width="80"
	          align="center"
	        >
	          <template slot-scope="scope">
	            <el-button
	              type="danger"
	              icon="el-icon-delete"
	              size="mini"
	              circle
	              @click="removeItem(scope.$index)"
	            ></el-button>
	          </template>
	        </el-table-column>
	      </el-table>
	    </div>
	
	    <!-- Footer 部分 -->
	    <div class="dialog-footer">
	      <div class="total-info">
	        <!-- <span>合计数量：{{ totalQuantity }}</span> -->
	        <span style="margin-left: 20px;">合计金额：{{ lsValue }} 元</span>
	      </div>
	      <div class="action-buttons" style="padding: 20px;text-align:right;">
	        <el-button type="primary" @click="confirmTransfer" size="small" :disabled="!targetWarehouse || tableDetailsData.length === 0"
	        >确认调拨</el-button>
	        <el-button @click="cancelTransfer" size="small">取消</el-button>
	      </div>
	    </div>
	  </el-dialog>
</div>

</div>
</template>

<script>
// self
import AccType from './exaStoreType.js'
import addForm from './addForm.js' //Form表单
// prop

// ext

// 接口
import { 
	getPurctcmdocPage,toExaminePurctcmdoc,selectDropDownList,
	} from "@/api/systemCatalogue/traMedici.js";
	// 接口 快捷调拨
	import { fastTransfer } from "@/api/systemCatalogue/traMedici.js";
export default {
	props: ['parentMethod'],
	inject: ['reload'], // 无痕刷新
	components:{
		
	},
	data(){
		return{
			//str
			diglogTile:'', // 动态页面的动态标题
			tableWidth:'', //右侧表格动态宽度
			totalAmt:'', //合计金额
			value:'',
			deptCode:'',
			cbValue:'',
			lsValue:'',
			getLunarDay: '',
			areaCode:'',
			areaPName:'',
			idx:'',
			//num
			
			//ble
			disabled:true,
			toPassDialog:false, // 快捷调拨
			totaldisabled:true,
			exaDialogVisible:false,
			dialogFormVisible:false,
			//arr
			formType:[],
			tableData:[],
			selectOption:[{id:'2',label:'中药库',value:'中药库'}],
			targetWarehouse: 2, // 默认选择中药库
			warehouseOptions: [
				{ id: 2, name: '中药库' },
			],
			tableDetailsData: [],
			currentWarehouse: '中药库', // 当前库房，不可修改
			ghdwOption:[],
			nameOption:[],
			tableRows:[
				{ name:"系统序号", prop:"drugId",  },{ name:"药品编码", prop:"drugCode",  },
				{ name:"药品名称", prop:"drugName", type:""},{ name:"规格描述", prop:"drugSpec", type:"" },
				
				{ name:"采购数量", prop:"purcCnt", nz:"nz" },{ name:"入库单位", prop:"unt", type:"" },{ name:"成本单价", prop:"purcPric", type:"" },
				{ name:"参考金额", prop:"salePric", type:"" },{ name:"生产厂家", prop:"prodentpName", type:"" },
				{ name:"生产批号", prop:"manuLotnum", type:"" },
			],
			// 入库方式
			rkWaysOptions:[
				{id:1,label:'采购入库',value:'采购入库'},{id:2,label:'其他入库',value:'其他入库'},
				{id:3,label:'赠送入库',value:'赠送入库'},{id:4,label:'盘点单位',value:'盘点单位'},{id:5,label:'系统切换入库',value:'系统切换入库'}
			],
			//obj
			addForm:{}, // form表单 * saleAmt
			options:[],
			ssrOption:[],
			gysOption:[],
		}
	},
	computed: {
	    totalQuantity() {
	      return this.tableDetailsData.reduce((sum, item) => sum + item.quantity, 0)
	    },
	    totalAmount() {
	      return this.tableDetailsData.reduce((sum, item) => sum + (item.quantity * item.price), 0).toFixed(2)
	    },
	},
	// 过滤器
	filters: {
		// 千位分隔符
	    currencyFormat(value) {
	      if (value === null || value === undefined) return '0.00';
	      const num = Number(value);
	      if (isNaN(num)) return '0.00';
	      return num.toLocaleString('zh-CN', {
	        minimumFractionDigits: 2,
	        maximumFractionDigits: 2
	      });
	    }
	},
	mounted() {
		// 获取接口参数
		this.getAddForm();
		this.getGys();
		// 定义数据来源
		this.formType = AccType.map(function(val) { return val })
		// 获取制单人 => 当前登录用户
		// this.addForm.createId = JSON.parse(localStorage.getItem('userInfo')).userId;
	},
	methods:{
		// 打开model 获取采购计划数据
		async openModel(parm){
			this.diglogTile = parm.name
			this.exaDialogVisible = true;
			let res = await getPurctcmdocPage({id:parm.id});
			// res.data.content.remark = res.data.remark
			// res.data.content.supplierName = res.data.content.supplyCandidateName
			// 遍历 res.data 的所有键名
			for (let key in res.data) {
			  // 检查键名是否在对象 A 中存在
			  if (this.addForm.hasOwnProperty(key)) {
			    // 如果存在，将 B 中的值更新到 A 中
			    this.addForm[key] = res.data[key];
			  }
			}
			console.log(this.addForm,'获取合并之后的采购入库');
			// 计算总金额
			// 使用 reduce 方法将 saleAmt 的值相加
			this.cbValue =res.data.tcmDocDetails.reduce((total, item) => {
			  return total + parseFloat(item.saleAmt); // 将 saleAmt 转换为数字并累加
			}, 0); // 初始值为 0
			this.addForm.id = parm.id
			this.totalAmt = res.data.totalAmt
			this.tableData = res.data.tcmDocDetails

		},
		async getGys(){
			// 供应商下拉列表
			let rs = await selectDropDownList();
			this.gysOption = rs.data.content.map(obj => {
			  // 将 name 替换为 label，并保留其他字段
			  return { label: obj.supplierName , ...obj };
			});
		},
		deleteRow(index, rows) {
		  rows.splice(index, 1);
		},
		handleSelectCost(val) {
		  this.addForm.nativePlace = val.join(',')
		},
		// testA(val){
		// 	console.log(val);
		// },
		// 键盘事件
		 handleKeyup(event) {
		  // 检查按键
		  if (event.key === 'Enter') {
			// 执行相应的动作
		  }
		},
		testDate(val,i){
			this.idx = val.id
		},
		handleClose(done) {
			done();
		},
		// 确定提交
		async Submit(){
			console.log(this.addForm);
			let result = await toExaminePurctcmdoc({
				id:this.addForm.id,
				state: 2
			})
			if (result.code === 200) {
				this.$message({ type: 'success', message: '已提交！'});
				this.refreshParent(); // 使用新的刷新方法
				this.exaDialogVisible = false;
			} else {
				this.$message.error('失败！'+res.message)
			}
		},
		//确定审核
		async exaSubmit(){
			console.log(this.addForm);
			let result = await toExaminePurctcmdoc({
				id:this.addForm.id,
				state: 4
			})
			if (result.code === 200) {
				this.$message({ type: 'success', message: '已审核！'});
				this.refreshParent(); // 使用新的刷新方法
				this.exaDialogVisible = false;
			} else {
				this.$message.error('审核失败！'+res.message)
			}
		},
		// 拒绝审核
		refuseExamine(){
			this.$confirm('此操作将回退该条数据状态, 是否继续?', '提示', {
			  confirmButtonText: '确定',
			  cancelButtonText: '考虑一下',
			  type: 'warning'
			}).then(async() => {
				let result = await toExaminePurctcmdoc({
					id:this.addForm.id,
					state: 0
				})
				if (result.code === 200) {
					this.refreshParent(); // 使用新的刷新方法
					this.exaDialogVisible = false;
				} else {
					this.$message.error('不准不审核！'+res.message)
				}
			}).catch(() => {
				this.$message({ type: 'info', message: '考虑一下'});          
			});
		},
		//确定过单
		async passOrderSubmit(){
			console.log(this.addForm,'过单数据');
			let result = await toExaminePurctcmdoc({
				id:this.addForm.id,
				state: 5
			})
			if (result.code === 200) {
				this.$message({ type: 'success', message: '已过单！'});
				this.parentMethod(); // 更新数据驱动 => 父组件 shopPlan
				this.openToPass();
				this.exaDialogVisible = false;
			} else {
				this.$message.error('过单失败！'+res.message)
			}
		},
		// 执行快捷调拨逻辑
		async openToPass(){
			// console.log('执行快捷调拨逻辑');
			// 检查是否显示快捷调拨提示
			const quickTransfer = JSON.parse(sessionStorage.getItem('quickTransfer') || 'true');
			console.log(quickTransfer,'quickTransfer')
			if (quickTransfer) {
			  try {
			    await this.$confirm('此单据已过单，是否要执行快捷调拨操作?', '提示', {
			      confirmButtonText: '确定',
			      cancelButtonText: '取消',
			      type: 'info'
			    });
			    
			    // 确保关闭当前对话框后再打开调拨对话框
			    this.exaDialogVisible = false;
			    await this.$nextTick(); // 等待DOM更新
			    
			    // 执行快捷调拨逻辑
			    console.log('执行快捷调拨逻辑');
			    await this.toPassOrder();
			  } catch (error) {
			    this.$message.info('已取消快捷调拨');
			  }
			} else {
			  this.exaDialogVisible = false;
			}
		},
		// 拒绝过单
		refusePassOrder(){
			this.$confirm('此操作将回退该条数据状态, 是否继续?', '提示', {
			  confirmButtonText: '确定',
			  cancelButtonText: '考虑一下',
			  type: 'warning'
			}).then(async() => {
				console.log(this.addForm);
				let result = await toExaminePurctcmdoc({
					id:this.addForm.id,
					state: 2
				})
				if (result.code === 200) {
					this.refreshParent(); // 使用新的刷新方法
					this.exaDialogVisible = false;
				} else {
					this.$message.error('不准不过单！'+res.message)
				}
			}).catch(() => {
				this.$message({ type: 'info', message: '考虑一下'});          
			});
		},
		// 草稿保存
		async draftSubmit(){
			 this.addForm.list.push(this.lists)
			 this.addForm.totalAmt = this.cbValue
			 this.addForm.state = 0
			 console.log(this.addForm);
			 let result = await addPurchasingPlan(this.addForm)
			 if (result.code === 200) {
			 	this.$message({
			 		type: 'success',
			 		message: '采购计划草稿：已保存！',
			 	});
			 	this.refreshParent(); // 使用新的刷新方法
			 	this.exaDialogVisible = false;
			 } else {
			 	this.$message.error('失败！')
			 }
		},
		// 快捷调拨
		async toPassOrder() {
		  try {
		    // 1. 获取数据
		    await this.getData();
		    
		    // 2. 确保关闭所有其他对话框
		    this.exaDialogVisible = false;
		    
		    // 3. 等待Vue更新DOM
		    await this.$nextTick();
		    
		    // 4. 设置调拨对话框可见
		    this.toPassDialog = true;
		    
		    // 5. 再次等待确保DOM更新
		    await this.$nextTick();
		    
		    console.log('调拨对话框状态:', this.toPassDialog);
		    
		    // 6. 调试DOM元素
		    this.$nextTick(() => {
		      const dialog = document.querySelector('.quick-transfer-dialog');
		      // console.log('对话框元素:', dialog);
		      // if (dialog) {
		      //   console.log('对话框样式:', window.getComputedStyle(dialog));
		      // }
		    });
		  } catch (error) {
		    // console.error('快捷调拨出错:', error);
		    this.$message.error('调拨操作初始化失败');
		  }
		},
		openDialog() {
		    this.toPassDialog = true
		},
		cancelTransfer() {
		  this.toPassDialog = false
		  this.$message.info('已取消调拨操作')
		},
		async confirmTransfer() {
		  // 这里添加调拨逻辑
		  let result = await fastTransfer(this.abc);
		  this.abc.phayId = this.targetWarehouse;
		  // console.log(this.abc,'快捷调拨操作');
		  	if (result.code === 200) {
		  		this.$message({ type: 'success', message: result.message });
		  		this.reload(); // 更新数据驱动 => 父组件 shopPlan
		  		this.addDialogVisible = false;
		  	} else {
		  		this.$message.error(result.message)
		  	}
		  // this.$message.success('调拨操作成功')
		  this.toPassDialog = false
		},
		removeItem(index) {
		  this.tableDetailsData.splice(index, 1)
		  this.$message.success('已移除该药品')
		},
		// 修改后的刷新方法
		  refreshParent() {
		    // 调用父组件方法刷新
		    if (this.parentMethod) {
		      this.parentMethod(); // 调用父组件传入的刷新方法
		    }
		    this.reload(); // 刷新子组件
		  },
		  
		//sons
		// db events
		handledbRow(row, column, event){
			if(row){ this.form = row; this.watchDialogVisible = true } else { console.log('fail'); }
			// console.log(this.form);
			this.formdisabled = true
			// this.form.textSpell = this.makePy(this.form.label).toLocaleUpperCase()
			// console.log(this.form.textSpell);
		},
		// col 里面包含了表头字段和名称，list 是表格数据
		columnWidth(col, list) {
		  let prop = col.prop,lab = col.lab;
		  let width = 40; // 设定一个最小值
		  let maxlenStr = ""; // 最长字符串
		  for (let info of list) {
			if (maxlenStr < (info[prop] + "").length) maxlenStr = info[prop];
		  }
		  width = Math.max(width, len(lab), len(maxlenStr));
		  // 表格自带的内边距(20px) 自调
		  return width + 24; // 这里加了 12px
		  function len(str) {
			// 实际分配长度可根据需要自行调整
			let length = 12;
			for (const char of str + "") {
			  // 英文小写字符 8px
			  if ("a" <= char && char <= "z") length += 8;
			  // 英文大写字符 8px
			  else if ("A" <= char && char <= "Z") length += 8;
			  // 中文字符 28px
			  else if (char >= "\u4e00" && char <= "\u9fa5") length += 28;
			  // 其他 8px
			  else length += 12;
			}
			return length;
		  }
		},
		// 挂载或销毁前后重新赋值后端参数
		getAddForm(){
			// 左侧提交表单
			this.addForm = addForm.map(v => {return v })[0]; // Form
			this.addMainForm = this.addForm.tcmDocDetails[0]
			console.log(this.addForm,'原始的接口参数数据');
			// 定义数据来源
			this.formType = AccType.map(function(val) { return val })
			// 解构赋值排除 list 属性 => 弃用
			// this.addHeadrForm = addForm.map(item => { let { list, ...newItem } = item; return newItem })[0];
		},
	},
	
}
</script>

<style lang="less" scoped>
.layout-app{
    width: 100%;
    height: 100%;
    display: flex;
	background-color: f8f8f8;
	/deep/ .el-dialog__header{
		padding: 4px;
		background-color: #007bb0;
	}
	
	/deep/ .el-form-item--mini.el-form-item, .el-form-item--small.el-form-item{
		margin-bottom: 8px;
	}
	/deep/ .el-dialog__title{
		font-size: 12px;
		color: #fff;
	}
	/deep/ .el-dialog__headerbtn {
		top: 10px;
	}
	/deep/ .el-dialog__headerbtn .el-dialog__close{
		color: #fff;
	}
	/deep/ .el-dialog__headerbtn .el-dialog__close:hover{
		background-color: brown;
	}
	/deep/ .el-dialog__body{
		padding: 8px;
	}
	/deep/ .el-divider--horizontal{
		margin: 0;
	}
	/deep/ .el-form-item__label{
		display: flex;
		justify-content: right;
		font-size: 12px;
	}
    .addAcc{
		// 选项卡
		.tabs{
			
			.tabsMain{
				display: flex;
				flex-direction: column;
				justify-content: space-between;
				align-items: center;
				width: 100%;
				margin-bottom: 8px;
				/deep/ .el-select > .el-input{
					width: 100%;
				}
				/deep/ .el-date-editor.el-input, .el-date-editor.el-input__inner{
					width: 100%;
				}
				.table{
					width: 100%;
					margin-top: 12px;
					/deep/ .el-table .cell{
						font-size: 12px;
						font-weight: 400;
						color: #0c0c0c;
						text-align: left;
					}
					/* 自定义高亮颜色 */
					::v-deep .el-table__body tr.current-row > td {
					  background-color: #00557f !important;
					  color: #f9f9f9; /* 可选：修改文字颜色 */
					}
					/deep/ .el-table .el-table__cell{
						padding: 8px 0;
					}
				}
				.total{
					display: flex;
					height: 48px;
					align-items: center;
					span{
						font-size: 12px;
					}
				}
			}	
		}
		.dialog-footer{
			display: flex;
			justify-content: right;
		}
	}
}
</style>